package toolkit.tianshi.common.regular;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 返回符合正则表达式的字符串
 * @author yulin
 */
public class Matching {

    /**
     * 返回符合正则表达式的完整字符串
     * @param rule 正则表达式
     * @param original 原始字符串
     * @return 符合正则表达式的完整字符串
     */
    public String matching (String rule, String original) {
        Pattern pattern = Pattern.compile(rule);
        Matcher matcher = pattern.matcher(original);
        StringBuilder stringBuilder = new StringBuilder();
        while (matcher.find()) {
            String group = matcher.group();
            stringBuilder.append(group);
        }
        return stringBuilder.toString();
    }

    /**
     * 返回符合正则表达式的所有字符串
     * @param rule 正则表达式
     * @param original 原始字符串
     * @return 符合正则表达式的所有字符串
     */
    public String[] matchings (String rule, String original) {
        Pattern pattern = Pattern.compile(rule);
        Matcher matcher = pattern.matcher(original);
        List<String> list = Lists.newArrayList();
        while (matcher.find()) {
            String group = matcher.group();
            list.add(group);
        }
        return list.toArray(new String[]{});
    }
}
